//
//  UserAccountViewModel.swift
//  新浪微博(day01练习)
//
//  Created by KeY on 16/1/12.
//  Copyright © 2016年 KeY. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {

    var userAccount: UserAccount?
    override init() {
        userAccount = UserAccount.loadUserAccount()
        super.init()
    }
    
    var userLogin: Bool {
    
        return userAccount?.access_token != nil
        
    }
    //获取授权的token
    func loadAccessToken(code: String) {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret": client_secret, "grant_type":"authorization_code","code": code,"redirect_uri": redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            guard let dict = result as? [String : AnyObject] else {
            
                print("数据格式不合法")
                return
            }
            let account = UserAccount(dict: dict)
            print(account)
            self.loadUserInfo(account)
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    private func loadUserInfo(account: UserAccount) {
        //准备URl
        let urlString = "https://api.weibo.com/2/users/show.json"
        //保证这里有值
        let parameters = ["access_token": account.access_token!,"uid": account.uid!]
        //获取AFN对象
        let AFN = AFHTTPSessionManager()
        //调用GET方法44
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            guard let dict = result as? [String : AnyObject] else {
            print("数据格式不合法")
                return
                
            }
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            
            account.name = name
            account.avatar_large = avatar_large
            account.saveAccount()
            
            
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
}



















